package com.haoyun.mirage.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.haoyun.common.constant.CommonConstant;
import com.haoyun.common.core.Result;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.ERROR_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;

/**
 * Created by twg on 2018/4/14.
 * 自定义error过滤器，必须要在SendErrorFilter之前运行，不然不能显示json格式的自定义异常信息。
 *
 * @see org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter
 */
@Slf4j
@Component
public class SendJsonErrorFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return ERROR_TYPE;
    }

    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getThrowable() != null;
    }

    @Override
    public Object run() {
        log.info("==========This is SendJsonErrorFilter =======");
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = context.getResponse();
        Object throwable = context.get("throwable");
        if (throwable != null && throwable instanceof ZuulException) {
            // Remove error code to prevent further error handling in follow up filters
            context.remove("throwable");
            // Populate context with new response values
        }
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        response.setStatus(HttpStatus.SC_FORBIDDEN);
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(Result.buildErrorResult(HttpStatus.SC_FORBIDDEN, throwable)));
        } catch (IOException e) {
            log.error("This is printWriter error. {}", e);
        }
        return null;
    }
}
